package com.cskaoyan.controller.wx;

import com.cskaoyan.bean.BaseRespVo;
import com.cskaoyan.bean.InfoBean;
import com.cskaoyan.bean.User;
import com.cskaoyan.model.promote.vo.UserInfoVo;
import com.cskaoyan.service.UserLoginService;
import com.cskaoyan.shiro.MallToken;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("wx/auth")
public class WxLoginController {

    @Autowired
    UserLoginService userLoginService;


    @PostMapping("login")
    public BaseRespVo login(@RequestBody Map map, HttpServletRequest request){
        String username = (String) map.get("username");
        String password = (String) map.get("password");
        if(username == null || password == null){
            return BaseRespVo.fail();
        }
        MallToken mallToken = new MallToken(username, password, "wx");
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(mallToken);
        } catch (AuthenticationException e) {
            return BaseRespVo.errors();
        }
        // 此时登陆成功
        User user = userLoginService.getLoginInfo(username);

        Map<Object,Object> maps = new HashMap<>();
        long time = user.getLastLoginTime().getTime();
        time += 300000;
        UserInfoVo userInfo = new UserInfoVo();
        userInfo.setNickName(user.getNickname());
        userInfo.setAvatarUrl(user.getAvatar());
        maps.put("tokenExpire", time);
        maps.put("token", time);
        maps.put("userInfo", userInfo);
        return BaseRespVo.ok(maps);
    }

    @RequestMapping("logout")
    public BaseRespVo logout(){
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return BaseRespVo.ok();
    }
}
